﻿using MT.WebApi.Core.Auth.OverWrite;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using MT.Common.Log;
using MT.Common.Helpers;
using MT.Common.Helper;

namespace MT.WebApi.Core.Filters
{
    public class SampleDomainService
    {
    }
    public class GlobalAuthorizationFilter : Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter
    {




        public void OnAuthorization(AuthorizationFilterContext context)
        {

            if (context.ActionDescriptor.EndpointMetadata.Any(e => (e as Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute) != null))
                return;
            #region ip 验证

            #endregion


            var authorization = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();

            if (string.IsNullOrEmpty(authorization))
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Result = new ObjectResult(new { Code = 401, Msg = "请获取授权" });
                return;
            }
            var jwt = JwtHelper.SerializeJwt(authorization);
            if (jwt == null)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Result = new ObjectResult(new { Code = 401, Msg = "令牌错误" });
                return;
            }
            if (jwt.ExpireTime < DateTime.Now)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Result = new ObjectResult(new { Code = 401, Msg = "token 已过期" });
                return;
            }
        }

    }
}
public class SkipAttribute : Attribute
{
}

